var menuUrlOfThisPage = window.document.location.pathname.substring(1);
menuUrlOfThisPage = menuUrlOfThisPage.substring(menuUrlOfThisPage.indexOf("/")+1);
var rootPathWithSlash = window.location.href.substring(0, window.location.href.length - window.location.search.length);
rootPathWithSlash = rootPathWithSlash.substring(0, rootPathWithSlash.length - menuUrlOfThisPage.length);

$(function() {
	var butt = '<input type="button" class="easyui-linkbutton" onclick="assemDataAndSend()"' +
			' value="导出Excel" style="float:right"/>';
	$('[onclick="cx()"]').after(butt);
});

function assemDataAndSend() {
	addLoadingMask();
	var url = window.location.href;
	$.ajax({
		type : "GET",
		url : url,
		success : function(pageCode) {
			send(pageCode);
		}
	});
}

function send(pageCode) {
	var pageNumber = 1;
	var pageSize = 20000;
	var formData = $("form:first").serializeObject();
	formData.page = pageNumber;
	formData.rows = pageSize;
	var dgObj = window.dg.datagrid("options");
	if (dgObj == null) {
		alert("无法获取数据，请联系后台人员");
		removeLoadingMask();
	}
	formData.sort = dgObj.sortName;
	formData.order = dgObj.sortOrder;
	var urlData = {
			queryMethod:dgObj.method,
			queryUrl:window.location.protocol + "//" + window.location.host + dgObj.url,
			pageUrl:window.menuUrlOfThisPage
	};
	
	var fix = "--------";
	var separator = fix + "entity_separator" + fix;
	var dgObj = window.dg.datagrid("options");
	var columnsCode = objectArrayToString(dgObj.columns[0]);
	var data = "formData:" + JSON.stringify(formData) + separator + 
			"urlData:" + JSON.stringify(urlData) + separator + 
			"pageCode:" + pageCode + separator + "columnsCode:" + columnsCode;
	$.ajax({
		url: rootPathWithSlash + "report/commonExcel/pushPageData",
		type: 'POST',
		data: data,
		dataType: 'text',
		success: function(result) {
			alert(result);
			removeLoadingMask();
		},
		error: function(xhr) {
			alert("请求失败");
			removeLoadingMask();
		}
	});
}

function objectArrayToString(array) {
	if (array.length == 0) {
		return "[]";
	}
	var str = "[";
	array.forEach(function(item, index, array) {
		str += "{";
		for (var key in item) {
			if (typeof item[key] == "string") {
				str += key + ":'" + item[key] + "',";
			} else {
				str += key + ":" + item[key] + ",";
			}
		}
		str = str.substring(0, str.length-1) + "},";
	});
	return str.substring(0, str.length-1) + "]";
}

function addLoadingMask() {
	$("<div class=\"datagrid-mask\"></div>")
			.css({ display: "block", width: "100%", height: $(window).height() })
			.appendTo("body");
	$("<div class=\"datagrid-mask-msg\"></div>").html("正在处理，请稍候。。。")
			.appendTo("body").css({ display: "block",
			left: ($(document.body).outerWidth(true) - 190) / 2,
			top: ($(window).height() - 45) / 2 });
}

function removeLoadingMask() {
	$(".datagrid-mask").remove();
	$(".datagrid-mask-msg").remove();
}